package Thread_study.timer;

import java.util.Date;
import java.util.TimerTask;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * ScheduledExecutorService线程池做定时器
 * 因为是基于线程池,所以某个任务的执行情况不会影响其他定时任务的执行
 *
 */
public class TimerDemo2 {
    public static void main(String[] args) {
        // 1.创建ScheduledExecutorService线程池,做定时器
        ScheduledExecutorService pool = Executors.newScheduledThreadPool(3);

        // 2.开启定时任务
        pool.scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {
                System.out.println(Thread.currentThread().getName() + "执行输出:AAA ==>" + new Date());
                try {
                    System.out.println("AAA休眠");
                    Thread.sleep(10000);
                } catch (InterruptedException e) {
                    e.getStackTrace();
                }
            }
        }, 0, 2, TimeUnit.SECONDS);

        pool.scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {
                System.out.println(Thread.currentThread().getName() + "执行输出:BBB ==>" + new Date());
                System.out.println(10 / 0);
            }
        }, 0, 2, TimeUnit.SECONDS);

        pool.scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {
                System.out.println(Thread.currentThread().getName() + "执行输出:CCC ===>" + new Date());
            }
        }, 0, 2, TimeUnit.SECONDS);



    }
}
